package com.supreme.commonboot.utils;

import org.springframework.beans.BeansException;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

@Component
public class GlobalSpringUtils implements ApplicationContextAware {

    private static AnnotationConfigServletWebServerApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        GlobalSpringUtils.applicationContext = (AnnotationConfigServletWebServerApplicationContext) applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return GlobalSpringUtils.applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return GlobalSpringUtils.applicationContext.getBean(clazz);
    }

    public static ConfigurableEnvironment getEnvironment() {
        return GlobalSpringUtils.applicationContext.getEnvironment();
    }

}
